package org.fenixsoft.jvm.chapter7.my;

import groovy.lang.GroovyClassLoader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.concurrent.TimeUnit;

/**
 * GroovyClassLoader 将String编译并通过内部类InnerLoader加载到JVM，
 * 不缓存已经加载的Class
 */
public class GroovyClassLoaderTest {
    public static final GroovyClassLoader CLASS_LOADER = new GroovyClassLoader();
    public static final String DEMO_OBJ_TXT = "public class DemoObj {\n" +
            "    @Override\n" +
            "    public String toString() {\n" +
            "        return \"I am DemoObj\";\n" +
            "    }\n" +
            "}";

    public static void main(String[] args) {
        //loadClass(DEMO_OBJ_TXT);
        loadClassTimer(new File("E:\\Java\\idea project\\UnderstandingTheJvm3\\src\\org\\fenixsoft\\jvm\\chapter7\\my\\DemoObj.txt"));
    }

    public static void loadClassTimer(File file) {
        for (int i = 0; i < 100; i++) {
            loadClass(file);

            System.out.println("##################");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                return;
            }
        }
    }

    public static void loadClass(File file){
        try (FileReader fileReader = new FileReader(file);
             BufferedReader bufferedReader = new BufferedReader(fileReader);) {

            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                builder.append(line);
            }
            loadClass(builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void loadClass(String code){
        Class demoObjClass = CLASS_LOADER.parseClass(code);
        try {
            Object instance = demoObjClass.newInstance();

            System.out.println(instance.toString());

            /*ClassLoader classLoader = demoObjClass.getClassLoader();
            while (classLoader != null) {
                System.out.println(classLoader);
                classLoader = classLoader.getParent();
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
